﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FillCartridgeBBB.Models;

namespace FillCartridgeBBB.Controllers
{
    public class FillController : Controller
    {
        private DataManager _dataManager = null;

        public FillController (DataManager dataManager)
        {
            _dataManager = dataManager;
        }

        public ActionResult List()
        {
            ViewData.Model = _dataManager.Fills.SelectAll();
            return View();
        }

        public ActionResult Deliver()
        {
            ViewData["Customers"] = new SelectList(_dataManager.Customers.SelectAll(), "CustomerId", "Name");
            ViewData["Cartridges"] = _dataManager.Cartridges.SelectEmpty();
            return View();
        } 

        [HttpPost]
        public ActionResult Deliver(FormCollection collection)
        {
            var customer = collection["CustomerId"];
            var cartridge = collection["CartridgeId"];
            var cart = cartridge.Split(',');
            List<Cartridge> cartridges = new List<Cartridge>();
            foreach (var cartridgeId in cart)
            {
                if (cartridgeId != "false")
                {
                    cartridges.Add(_dataManager.Cartridges.SelectById(int.Parse(cartridgeId)));
                    _dataManager.Cartridges.NextState(int.Parse(cartridgeId));
                }
            }
            _dataManager.Fills.Insert(cartridges, customer);
            return RedirectToAction("List");
        }
        

        public ActionResult Return()
        {
            ViewData.Model = _dataManager.Fills.SelectForReturn();
            return View();
        }


        [HttpPost]
        public ActionResult Return(FormCollection collection)
        {
            var ids = collection["FillId"].Split(',');
            var toners = collection["Toner"].Split(',');
            var barabans = collection["Baraban"].Split(',');
            var others = collection["Other"].Split(',');
            var notes = collection["Note"].Split(',');

            _dataManager.Fills.Edit(ids, toners, barabans, others, notes);
            return RedirectToAction("List");
        }

        //
        // GET: /Fill/Delete/5
 
        public ActionResult Delete(int id)
        {
            //_dataManager.Cartridges.PriorState(_dataManager.Fills.SelectById(id).Cartridge.CartridgeId);
            _dataManager.Fills.Delete(id);
            return RedirectToAction("List");
        }
    }
}
